<!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8">
	<title></title>
	<style>
		.myBorder {
			width: 80%;
			min-height: 50px;
			border: 1px solid red;
			margin: 5px auto;
			padding: 5px;
		}
	</style>
	<script src="vue.js"></script>
</head>

<body>
	<div id="app">
		<div class="myBorder">
			watch监听简单数据<br />
			a的值:{{a}}
			<br />
			<button type="button" @click="add1">每次加1</button>
			<br />
			b的值:{{b}}
			<br />
			<button type="button" @click="add2">每次加1</button>
		</div>
		<div class="myBorder">
			watch监听复杂数据obj==>引用数据类型<br />
			<label>
				姓名1:<input type="text" v-model="obj1.user" />
			</label>
			<br />
			<button type="button" @click="add3">添加3</button>
			<br />
			<label>
				姓名2:<input type="text" v-model="obj2.user" />
			</label>
			<br />
			<button type="button" @click="add4">添加4</button>
		</div>
	</div>
	<script>
		var vm = new Vue({
			el: "#app",
			data: {
				a: 0,
				b: 0,
				obj1: {
					user: ""
				},
				obj2: {
					user: ""
				},
				arr3: [],
				arr4: []
			},
			methods: {
				add1() {
					this.a++;
				},
				add2() {
					this.b++;
				},
				add3() {
					this.arr3.unshift(this.obj1.user);
					console.log("arr3:", this.arr3);
				},
				add4() {
					this.arr4.unshift(this.obj2.user);
					console.log("arr4:", this.arr4);
				}
			},
			computed: {

			},
			watch: {
				a: function (newVal, oldVal) {
					console.log("a newVal:", newVal, "oldVal", oldVal);
				},
				obj1: {
					handler: function (newVal, oldVal) {
						console.log("obj1 newVal:", newVal, "oldVal", oldVal, newVal === oldVal);
					},
					deep: true,
					immediate: true
				},
				arr3: {
					handler: function (newVal, oldVal) {
						console.log("arr3 newVal:", newVal, "oldVal", oldVal, newVal === oldVal);
					},
					deep: true,
					immediate: true
				}
			}
		});
		var unwatch = vm.$watch("b", function (newVal, oldVal) {
			console.log("b newVal:", newVal, "oldVal", oldVal);
			if (newVal == 10) {
				unwatch(); //清除对b的监听
			}
		});
		//			setTimeout(function(){
		//				unwatch();
		//			},5000);

		// expOrFn:要观测的属性
		// callback:可以是一个回调函数, 也可以是一个纯对象(这个对象要包含handle属性)
		// options: {deep, immediate}, deep指的是深度观测, immediate立即执行回调

		vm.$watch("obj2", function (newVal, oldVal) {
			console.log("obj2 newVal:", newVal, "oldVal", oldVal, newVal === oldVal);
		}, {
			deep: true,
			immediate: true
		});

		vm.$watch("arr4", function (newVal, oldVal) {
			console.log("arr4 newVal:", newVal, "oldVal", oldVal, newVal === oldVal);
		}, {
			deep: true,
			immediate: true
		});
	</script>
</body>

</html>